//
//  SFSwizzle.m
//  Pods-SFNavigationBarManager_Example
//
//  Created by shen on 2021/11/17.
//

#import "SFSwizzle.h"
#import <objc/runtime.h>

void SFSwizzleMethod(Class originalCls, SEL originalSelector,
                     Class swizzledCls, SEL swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(originalCls, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(swizzledCls, swizzledSelector);

    BOOL didAddMethod = class_addMethod(originalCls,
                                        originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));

    if (didAddMethod) {
        class_replaceMethod(originalCls,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

@interface SFWeakObjectContainer : NSObject
@property (nonatomic, weak) id object;
@end

@implementation SFWeakObjectContainer

void sf_objc_setAssociatedWeakObject(id container, void *key, id value)
{
    SFWeakObjectContainer *wrapper = [[SFWeakObjectContainer alloc] init];
    wrapper.object = value;
    objc_setAssociatedObject(container, key, wrapper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

id sf_objc_getAssociatedWeakObject(id container, void *key)
{
    return [(SFWeakObjectContainer *)objc_getAssociatedObject(container, key) object];
}

@end


